package com.travel.server.manager.impl.command.user;

import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.user.QueryDepartmentListRequest;
import com.travel.server.manager.dto.response.user.QueryDepartmentListResponse;
import com.travel.server.manager.dto.response.user.QueryDepartmentListResponse.DepartmentItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.DepartmentDal;
import com.travel.server.manager.impl.dal.DepartmentDal.DepartmentParam;
import com.travel.server.manager.impl.dal.PageDto;
import com.travel.server.manager.model.DepartmentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/20 14:08
 * @Desc:
 */
@Component
public class QueryDepartmentListCommand extends AbstractCommand<QueryDepartmentListRequest, QueryDepartmentListResponse> {

    @Autowired
    private DepartmentDal departmentDal;

    @Override
    protected void checkInput(QueryDepartmentListRequest request) {

    }

    @Override
    public QueryDepartmentListResponse handle(QueryDepartmentListRequest request) {
        DepartmentParam param = makeParam(request);
        PageDto<DepartmentInfo> pageDto = departmentDal.select(param);
        return makeRespsonse(pageDto);
    }

    private QueryDepartmentListResponse makeRespsonse(PageDto<DepartmentInfo> pageDto){
        QueryDepartmentListResponse response = new QueryDepartmentListResponse();
        response.setTotalNum(pageDto.getTotal());
        List<DepartmentInfo> list = pageDto.getList();
        List<DepartmentItem> departmentList = new ArrayList<>();
        if(!CollectionUtil.isEmpty(list)){
            for(DepartmentInfo departmentInfo : list){
                DepartmentItem item = new DepartmentItem();
                item.setCreateTime(departmentInfo.getCreateTime());
                item.setDescribe(departmentInfo.getDepartmentDescribe());
                item.setName(departmentInfo.getDepartmentName());
                item.setId(departmentInfo.getId());
                departmentList.add(item);
            }
        }
        response.setDepartmentList(departmentList);
        return response;
    }

    private DepartmentParam makeParam(QueryDepartmentListRequest request){
        DepartmentParam param = new DepartmentParam();
        param.setLimit(request.getLimit());
        param.setOffset(request.getOffset());
        return param;
    }
}
